<template>
  <div class="search">
    <el-card>
     <el-row>
        <el-col :span="16">
          <el-form :model="searchForm" inline :label-width="100" class="search-form" style="width: 80%">
            <el-form-item label="品牌名称" prop="name">
              <el-input type="text" v-model="searchForm.name" clearable placeholder="请输入品牌名称" style="width: 160px" />
            </el-form-item>
            <el-form-item label="英文名称" prop="nameEn" >
              <el-input type="text" v-model="searchForm.nameEn" clearable placeholder="请输入品牌英文名" style="width: 160px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="8">
          <div>
          <el-button type="success" @click="showDialogAdd = true" style="margin-right: 80%" >添加品牌</el-button>
          </div>
        </el-col>
      </el-row>
      <el-table :data="tableData" style="width: 100%;" >
        <el-table-column fixed prop="id" label="品牌id" width="150" />
        <el-table-column prop="category.name" label="所属分类" width="120" />
        <el-table-column prop="name" label="品牌名" width="120" />
        <el-table-column prop="nameEn" label="品牌英文名" width="120" />
        <el-table-column prop="logo" label="图片" width="120" >
          <!-- 图片的显示 -->
          <template #default="scope">
            <el-image :src="scope.row.logo" style="min-width: 35px;height: 35px"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="country" label="所属国家" width="120" />
        <el-table-column prop="des" label="品牌描述" width="300" />
        <el-table-column prop="foundedTime" label="品牌创建时间" width="180" />
        <el-table-column prop="createTime" label="创建时间" width="400" />
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="toChangeBrand(scope.row)"
            >编辑</el-button>
            <el-button link type="danger" size="small" @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="total" @pagination="getPage" :limit="pageSize"></pagination>
    </el-card>
  </div>
  
<!--品牌添加-->
  <el-dialog v-model="showDialogAdd" title="新增品牌" width="32%" center>
      <el-form :model="brandForm" :rules="rules" ref="formRef" label-width="auto" style="max-width: 450px">
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="brandForm.categoryId"  style="width: 200px" clearable>
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="品牌名" prop="name">
          <el-input v-model="brandForm.name" placeholder="请填写品牌名"/>
        </el-form-item>
        <el-form-item label="英文名" >
          <el-input v-model="brandForm.nameEn" placeholder="请填写品牌英文名"/>
        </el-form-item>
        <el-form-item label="所属国家" prop="country">
          <el-input v-model="brandForm.country" placeholder="请填写所属国家"/>
        </el-form-item>
        <el-form-item label="logo" prop="logo">
          <div style="width: 100%;display: flex;justify-content: start;margin-top: 10px;">
            <el-upload
                class="avatar-uploader"
                action="http://localhost:8888/api/file/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="token"
            >
              <el-image v-if="brandForm.logo" w-full :src="brandForm.logo" class="avatar" style="min-width: 150px;height: 150px" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="描述" >
          <el-input v-model="brandForm.des" placeholder="请填写品牌描述"/>
        </el-form-item>
        <el-form-item label="创建时间" prop="foundedTime">
          <el-input v-model="brandForm.foundedTime" placeholder="请填写创建时间"/>
        </el-form-item>
      </el-form>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="showDialogAdd=false">取消</el-button>
      <el-button type="primary" @click="addBrand">确定</el-button>
    </span>
    </template>
  </el-dialog>

<!--品牌编辑-->
  <el-dialog v-model="showDialogChange" itle="品牌修改" width="32%" center>
    <div class="addressWrapper">
      <div style="text-align: center;margin-bottom:5%">
        <h2>品牌信息修改</h2>
      </div>
      <el-form :model="changeForm" :rules="rules" ref="formRef" label-width="auto" style="max-width: 450px">
        <el-form-item label="所属分类" prop="category">
          <el-select v-model="changeForm.category.name"  style="width: 200px">
            <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="品牌名" prop="name">
          <el-input v-model="changeForm.name" placeholder="请填写品牌名"/>
        </el-form-item>
        <el-form-item label="英文名" >
          <el-input v-model="changeForm.nameEn" placeholder="请填写品牌英文名"/>
        </el-form-item>
        <el-form-item label="所属国家" prop="country">
          <el-input v-model="changeForm.country" placeholder="请填写所属国家"/>
        </el-form-item>
        <el-form-item label="logo" prop="logo">
          <div style="width: 100%;display: flex;justify-content: start;margin-top: 10px;">
            <el-upload
                class="avatar-uploader"
                action="http://localhost:8888/api/file/upload"
                :show-file-list="false"
                :on-success="handleAvatarChangeSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="token"
            >
              <el-image v-if="changeForm.logo" w-full :src="changeForm.logo" class="avatar" style="min-width: 150px;height: 150px" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="描述" >
          <el-input v-model="changeForm.des" placeholder="请填写品牌描述"/>
        </el-form-item>
        <el-form-item label="创建时间" prop="foundedTime">
          <el-input v-model="changeForm.foundedTime" placeholder="请填写创建时间"/>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="showDialogChange=false">取消</el-button>
      <el-button type="primary" @click="changeBrand">确定</el-button>
    </span>
    </template>
  </el-dialog>
</template>

<script  setup>
import {onMounted, reactive, ref} from "vue";
import Pagination from "@/components/Pagination/index.vue";
import {beanUserAPI} from "@/api/userManage.js";
import { ElMessage } from "element-plus";
import 'element-plus/theme-chalk/el-message.css'
import {addBrandAPI, deleteBrandAPI, getBrandAPI, updateBasicAPI} from "@/api/brandManage.js";
import {Plus} from "@element-plus/icons";
import {useStore} from "vuex";
import {getChildNameAPI} from "@/api/categoryManage.js";
const current = ref(1)
const pageSize = ref(10)
const total = ref(100)
const categoryList = ref([{
  id:'',
  name:''
}])
//添加dialog
const showDialogAdd = ref(false)
//修改dialog
const showDialogChange = ref(false)

const tableData = ref([
  {
    id: '',
    category: [],
    name: '',
    nameEn: '',
    country:'',
    logo:'',
    des:'',
    foundedTime:'',
    createTime:''
  }
])
//添加form
const brandForm = ref({
    categoryId: '',
    name: '',
    nameEn: '',
    logo:'',
    country:'',
    des:'',
    foundedTime:'',
})

//修改form
const changeForm = ref({
  id:'',
  category: [],
  categoryId:'',
  name: '',
  nameEn: '',
  logo:'',
  country:'',
  des:'',
  foundedTime:'',
})
//查询form
const searchForm = reactive({
  name:null,
  nameEn:null,
})
const getBrand = async () => {
  const res = await getBrandAPI({current:current.value,pageSize:pageSize.value});
  tableData.value = res.data.records
  total.value = res.data.total
  console.log(tableData.value)
}
onMounted(() => getBrand())
const getPage = (params) => {
  current.value = params.page
  pageSize.value = params.limit
  if(searchForm){
    onSubmit()
  }else{
    getBrand()
  }
}
//条件搜索
const onSubmit = async ()=>{
  const name = searchForm.name
  const nameEn = searchForm.nameEn
  const params = ref({
    name:name,
    nameEn:nameEn,
    current:current.value,
    pageSize:pageSize.value
  })
  const res = await getBrand(params.value);
  tableData.value = res.data.records
  total.value = res.data.total
}
//点击编辑显示
const toChangeBrand = async (row) => {
  //查询分类信息
  changeForm.value  = row
  showDialogChange.value = true
}

/*品牌添加数据校验*/
const rules = {
  categoryId: [
    {required: true, message: '所属分类不能为空', trigger: 'blur'}
  ],
  name: [{required: true, message: '名称不能为空', trigger: 'blur'}],
  logo: [{required: true, message: 'logo不能为空', trigger: 'blur'}],
  country: [
    {required: true, message: '所属国家不能为空', trigger: 'blur'}
  ],
  foundedTime: [
    {required: true, message: '品牌创建时间不能为空', trigger: 'blur'}
  ],
}
const formRef = ref({})
const addBrand = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      const res = await addBrandAPI(brandForm.value)
      if (res.data) {
        showDialogAdd.value=false
        await getBrand()
        ElMessage.success("添加成功")
      }
    }

  })
}

// 展示商品图片上传成功
function handleAvatarSuccess(res) {
  brandForm.value.logo = res.data
}
function handleAvatarChangeSuccess(res){
 console.log("res.data",res.data)
  changeForm.value.logo = res.data
}
//展示商品图片上传前钩子
function beforeAvatarUpload(file) {
  console.log(file.type)
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    this.$message.error('上传图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
}
const store = useStore()
const token = {Authorization: store.getters.token}


//品牌信息修改
const changeBrand = async () => {
  changeForm.value.categoryId = changeForm.value.category.id
  const res = await updateBasicAPI(changeForm.value)
  if(res.data){
    await getBrand()
    showDialogChange.value=false
    ElMessage.success("修改成功")
  }
}

//品牌删除
const deleteRow = async (row) => {
  const res = await deleteBrandAPI(row.id)
  if(res.data){
    await getBrand()
    ElMessage.success("删除成功");
  }
}
//初始化挂载
const getCategory = async ()=>{
  const res = await getChildNameAPI()
  categoryList.value = res.data
}
onMounted(() => getCategory())

</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
<style scoped>

.search {
  .oss-operation {
    margin-bottom: 2vh;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;

    button {
      margin-right: 5px;
    }
  }
}
</style>